from rest_framework.views import APIView
from courses.models import Course, CourseTime
from rest_framework.response import Response
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework import status


# Create your views here.


class CartAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user_id = request.user.id
        redis = get_redis_connection('cart')
        cart_goods_list = redis.hgetall('cart_{}'.format(user_id))
        cart_goods_selects = redis.smembers('cart_selected_{}'.format(user_id))
        data_list = []
        try:
            for course_id_bytes, expire_bytes in cart_goods_list.items():
                course_id = int(course_id_bytes.decode())
                expire = expire_bytes.decode()
                course = Course.objects.get(pk=course_id)
                expires = course.coursetimes.all()
                expire_list = [{
                    'title': '永久有效',
                    'timer': -1,
                    'price': course.price
                }]
                for item in expires:
                    expire_list.append({
                        'title': item.title,
                        'timer': item.timer,
                        'price': item.price,
                    })
                try:
                    coursetime = CourseTime.objects.get(course=course_id, timer=expire)
                    price = coursetime.price
                except:
                    price = 0
                data_list.append({
                    'id': course_id,
                    'expire': expire,
                    'course_img': course.course_img.url,
                    'name': course.name,
                    'price': course.get_course_price(price),
                    'is_select': course_id_bytes in cart_goods_selects,
                    'expire_list': expire_list,
                })
        except:
            return Response(data_list, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        return Response(data_list, status=status.HTTP_200_OK)

    def post(self, request):
        course_id = request.data.get('course_id')
        try:
            Course.objects.get(pk=course_id, is_delete=False, is_show=True)
        except Course.DoesNotExist:
            return Response({'message': '当前课程不存在'}, status=status.HTTP_400_BAD_REQUEST)
        redis = get_redis_connection('cart')
        user_id = request.user.id
        try:
            pipeline = redis.pipeline()
            pipeline.multi()
            pipeline.hset('cart_{}'.format(user_id), course_id, -1)
            pipeline.sadd('cart_selected_{}'.format(user_id), course_id)
            pipeline.execute()
        except:
            return Response({'message': '添加课程到购物车失败！请联系客服人员'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
        count = redis.hlen('cart_{}'.format(user_id))
        return Response({'message': '成功添加课程到购物车！', 'count': count}, status=status.HTTP_200_OK)

    def put(self, request):
        user_id = request.user.id
        course_id = request.data.get('course_id')
        try:
            Course.objects.get(pk=course_id, is_delete=False, is_show=True)
        except Course.DoesNotExist:
            return Response({'message': '当前课程不存在'}, status=status.HTTP_400_BAD_REQUEST)
        is_select = request.data.get('is_select')
        redis = get_redis_connection('cart')
        if is_select:
            redis.sadd('cart_selected_{}'.format(user_id), course_id)
        else:
            redis.srem('cart_selected_{}'.format(user_id), course_id)
        return Response({'message': '修改购物车信息成功'}, status=status.HTTP_200_OK)

    def patch(self, request):
        user_id = request.user.id
        course_id = request.data.get('course_id')
        expire = request.data.get('expire')
        redis = get_redis_connection('cart')
        redis.hset('cart_{}'.format(user_id), course_id, expire)
        try:
            coursetime = CourseTime.objects.get(course=course_id, timer=expire)
            price = coursetime.course.get_course_price(coursetime.price)
        except:
            course = Course.objects.get(pk=course_id)
            price = course.get_course_price()
        return Response({'message': '修改购物车信息成功', 'price': price}, status=status.HTTP_200_OK)

    def delete(self, request):
        user_id = request.user.id
        course_id = request.query_params.get('course_id')
        redis = get_redis_connection('cart')
        pipeline = redis.pipeline()
        pipeline.multi()
        pipeline.hdel('cart_{}'.format(user_id), course_id)
        pipeline.srem('cart_selected_{}'.format(user_id), course_id)
        pipeline.execute()
        return Response({'message': '删除商品课程成功'}, status=status.HTTP_204_NO_CONTENT)
